﻿using System;
using System.Runtime.InteropServices;
using System.Text;

namespace svs.Mobile.BeyondMedia.UiCore
{
	/// <summary>
	/// THis code is based on a blog post from Andrew Arnott 
	/// http://blog.nerdbank.net/search/label/Smart%20devices
	/// </summary>
	public class PlatformDetection
	{
		#region SystemParametersInfoActions enum

		public enum SystemParametersInfoActions : uint
		{
			SPI_GETPLATFORMTYPE = 257, // this is used elsewhere for Smartphone/PocketPC detection 
			SPI_GETOEMINFO = 258
		}

		#endregion

		private const string MicrosoftEmulatorOemValue = "Microsoft DeviceEmulator";

		[DllImport("Coredll.dll", EntryPoint = "SystemParametersInfoW", CharSet = CharSet.Unicode)]
		private static extern int SystemParametersInfo4Strings(uint uiAction, uint uiParam, StringBuilder pvParam,
		                                                       uint fWinIni);
		private static string GetPlatformType()
		{
			StringBuilder platformType = new StringBuilder(50);
			if (
				SystemParametersInfo4Strings((uint) SystemParametersInfoActions.SPI_GETPLATFORMTYPE, (uint) platformType.Capacity,
				                             platformType, 0) == 0)
				throw new Exception("Error getting platform type.");
			return platformType.ToString();
		}

		private static string GetOemInfo()
		{
			StringBuilder oemInfo = new StringBuilder(50);

			if (SystemParametersInfo4Strings((uint) SystemParametersInfoActions.SPI_GETOEMINFO,
			                                 (uint) oemInfo.Capacity, oemInfo, 0) == 0)
				throw new Exception("Error getting OEM info.");
			return oemInfo.ToString();
		}

		public static bool IsSmartphone()
		{
			return GetPlatformType() == "SmartPhone";
		}
		public static bool IsPocketPC()
		{
			return GetPlatformType() == "PocketPC";
		}

		public static bool IsEmulator()
		{
			return GetOemInfo() == MicrosoftEmulatorOemValue;
		}
	}
}